<?php
/**
 * Created by PhpStorm.
 * User: king
 * Date: 2018/2/19
 * Time: 下午8:04
 */

/**
 * 封装api返回的数据格式
 */
if (!function_exists('response_api')) {
    function response_api($data, $message = 'success', $code = 0) {
        $data = $data ?? [];

        if (is_bool($data) && false === $data) {
            $code = 500;
        }

        $arr = [
            'code'    => $code,
            'message' => $message,
            'result'  => $data,
        ];

        $statusCode = 0 === $code ? 200 : $code;

        if ($data instanceof \Illuminate\Pagination\LengthAwarePaginator || 200 === $statusCode) {
            return $arr;
        }

        return response()->json($arr, $statusCode);
    }
}

/**
 * 获取pathinfo模式路由中的参数或参数列表
 */
if (!function_exists('route_param')) {
    function route_param(string $name = null) {
        $route = request()->route();

        if (!is_null($name)) {
            return $route->hasParameter($name) ? $route->parameter($name) : '';
        }

        return $route->parameters() ?? [];
    }
}

/**
 * 批量整合
 */
if (!function_exists('batch_merge')) {
    function batch_merge(array $resource, int $oneTime, Closure $callback) {
        $result = [];
        $count = count($resource);
        $totalNum = (int) ceil($count / $oneTime);

        for ($i=0; $i<$totalNum; $i++) {
            $nextStart = $i * $oneTime;
            $time = $oneTime + $nextStart;

            if ($time > $count) {
                $time = $count;
            }

            $result[] = $callback($nextStart, $time);
        }

        return $result;
    }
}

if (!function_exists('class_short_name')) {
    function class_short_name($className) {
        if (is_null($className)) {
            return $className;
        }

        return class_basename(get_class($className));
    }
}

if (!function_exists('query_log')) {
    function query_log() {
        return dd(\Illuminate\Support\Facades\DB::getQueryLog());
    }
}
